package LeetCode;

import java.util.LinkedList;
import java.util.Queue;

public class LC_547_FriendCircles {

    public static void main(String[] args) {

    }

    class Solution {
        public int findCircleNum(int[][] M) {
            if (M == null && M.length == 0) return 0;
            int n = M.length;
            boolean[] visited = new boolean[n];
            int count = 0;
            for (int i = 0; i < n; i++)
                if (dfs(M, i, visited) > 0)
                    count++;
            return count;
        }

        private int dfs(int[][] mat, int i, boolean[] visited) {
            if (visited[i]) return 0;
            visited[i] = true;
            int count = 1;
            for (int j = 0; j < visited.length; j++)
                if (i != j && mat[i][j] == 1)
                    count += dfs(mat, j, visited);
            return count;
        }

    }

    public class Solution_2 {
        void dfs(int[][] M, int[] visited, int i) {
            for (int j = 0; j < M.length; j++) {
                if (M[i][j] == 1 && visited[j] == 0) {
                    visited[j] = 1;
                    dfs(M, visited, j);
                }
            }
        }

        public int findCircleNum(int[][] M) {
            int[] visited = new int[M.length];
            int count = 0;
            for (int i = 0; i < M.length; i++) {
                if (visited[i] == 0) {
                    dfs(M, visited, i);
                    count++;
                }
            }
            return count;
        }
    }

    public class Solution_3 {

        Queue<Integer> q = new LinkedList<>();

        void bfs(int[][] M, int[] visited, int i) {
            q.offer(i);
            visited[i] = 1;
            while (!q.isEmpty()) {
                int node = q.poll();
                for (int j = 0; j < M.length; j++) {
                    if (visited[j] == 0 && M[node][j] == 1) {
                        q.offer(j);
                        visited[j] = 1;
                    }
                }
            }
        }

        public int findCircleNum(int[][] M) {
            int[] visited = new int[M.length];
            int count = 0;
            for (int i = 0; i < M.length; i++) {
                if (visited[i] == 0) {
                    bfs(M, visited, i);
                    count++;
                }
            }
            return count;
        }

    }
}